package managedbean.stakeholder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import org.primefaces.event.FileUploadEvent;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.localization.WebLocalization;

/**
 *
 * @author WenYong
 */
@ManagedBean
@RequestScoped
public class StakeholderAddUnstructuredContentUploadImageManager {

    private String imgUrl;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private String nextPage;
    private Long stakeholderId;
    @EJB
    private SystemMessagesBean systemMessages;
    @EJB
    private StakeholderSessionBeanStateless stakeholderSessionBean;
    private String preferredLocale;
    private WebLocalization localization;
    private String userName;
    private String panelTitle;
    //   private StakeholderAccountState stakeholderAccountState;

    /** Creates a new instance of StakeholderAddUnstructuredContentUploadImageManager */
    public StakeholderAddUnstructuredContentUploadImageManager() throws KeyStoreException {
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        KeyStore.getInstance("JKS");
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        stakeholderId = (Long) ctx.getExternalContext().getSessionMap().get("stakeholderId");
        userName = ctx.getExternalContext().getSessionMap().get("stakeholderUsername").toString();
        if (stakeholderId == null) {

            nextPage = (ctx.getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml")));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(nextPage);
            } catch (IOException ioe) {
                ioe.printStackTrace();

            }
        }

    }

    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException {
        try {
            if (ctx.getExternalContext().getSessionMap().containsKey("templateTitle")) {
                panelTitle = ctx.getExternalContext().getSessionMap().get("templateTitle").toString();
            }
            String strDirectory = userName + "/" + panelTitle;
            String panel = "";
            if (ctx.getExternalContext().getSessionMap().containsKey("Panel")) {
                panel = ctx.getExternalContext().getSessionMap().get("Panel").toString();
            }
            String fileName = panel;
            String filePath =
                    FacesContext.getCurrentInstance().getExternalContext().getRealPath("/images/upload/" + strDirectory);
            System.out.println("filePath is: " + filePath);

            File file = new File(filePath);
            if (!file.exists()) {
                if ((new File(filePath)).mkdirs()) {
                    System.out.println("Directory: " + strDirectory + " created");
                }
            }
            File result = new File(filePath + System.getProperty("file.separator") + fileName);
            FileOutputStream out = new FileOutputStream(result);

            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true) {
                a = is.read(buffer);

                if (a < 0) {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            imgUrl = "./../images/upload/" + userName + "/" + panelTitle + "/" + fileName;
            String statusMessage = systemMessages.getSystemMessage("UNSTRUCTURED_CONTENT_UPLOAD_IMAGE_SUCCESS", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, statusMessage));
            ctx.getExternalContext().getSessionMap().put("imageName", fileName);
        } catch (IOException e) {
            String statusMessage = systemMessages.getSystemMessage("UNSTRUCTURED_CONTENT_UPLOAD_IMAGE_FAILURE", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, statusMessage));
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String getImgUrl() {
        System.out.println(imgUrl);
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        System.out.println("set:" + imgUrl);
        this.imgUrl = imgUrl;
    }

    public void confirmImage() {
        String url = "";
        if (ctx.getExternalContext().getSessionMap().containsKey("returnPage")) {
            url = ctx.getExternalContext().getSessionMap().get("returnPage").toString();
        }
        try {
            String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/stakeholder/" + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
